'''
Created on Dec 1, 2011

@author: anorberg
'''

import sys
import csv
import tsvUtils
import os

if __name__ == '__main__':
    inFile = open(sys.argv[1], "r")
    rootFile = os.path.basename(sys.argv[1])
    outDir = sys.argv[2]
    os.makedirs(outDir)
    splitz = tsvUtils.cleave(csv.reader(inFile, dialect=csv.excel_tab), int(sys.argv[3]))
    print "Cloven."
    for key, value in splitz.iteritems():
        outFile = open(os.path.join(outDir, rootFile + "." + key), "w")
        for record in value:
            print >> outFile, "\t".join(record)
        outFile.flush()
        outFile.close()
        print "Wrote group", key
    